package service

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/model/dto"
)

type UserService struct {
}

func (*UserService) GetById(id uint) (user model.User, err error) {
	err = initialization.DB.Where("id = ?", id).First(&user).Error
	return
}

func (*UserService) Create(user *model.User) (err error) {
	hash := sha256.Sum256([]byte(user.Password))
	user.Password = hex.EncodeToString(hash[:])
	err = initialization.DB.Create(user).Error
	return
}

func (*UserService) Updates(user *model.User) (err error) {
	query := initialization.DB.Updates(user)
	if user.State == 0 {
		query = query.Update("state", 0)
	}
	if user.Gender == 0 {
		query = query.Update("gender", 0)
	}
	err = query.Error
	return
}

func (*UserService) Deletes(ids []int) (err error) {
	err = initialization.DB.Debug().Where("id in ?", ids).Delete(&model.User{}).Error
	return
}

func (u *UserService) Login(user *model.User) (uu model.User, err error) {
	var us model.User
	err = initialization.DB.Model(model.User{}).Where("username=?", user.Username).Scan(&us).Error
	hash := sha256.Sum256([]byte(user.Password))
	p1 := hex.EncodeToString(hash[:])
	if p1 != us.Password {
		return model.User{}, errors.New("账号或密码错误")
	}
	//123
	//err = initialization.DB.Where("username = ? and password = ?", user.Username, user.Password).First(user).Error
	return us, err
}

func (u *UserService) GetAll(param *dto.PageParam) (user []model.User, err error) {
	err = initialization.DB.Offset((param.PageNo - 1) * param.PageSize).Limit(param.PageSize).Find(&user).Error
	return
}

func (u *UserService) GetAllWithLike(param *dto.ParamUserAdmin) (user []model.User, err error) {
	query := initialization.DB.Offset((param.Page.PageNo-1)*param.Page.PageSize).Limit(param.Page.PageSize).Where("username like ? or nickname like ? or mobile like ?", "%"+param.Keywords+"%", "%"+param.Keywords+"%", "%"+param.Keywords+"%")
	if param.State != 0 {
		query = query.Where("state = ?", param.State-1)
	}
	// 时间不是零值
	if !param.Time.Start.IsZero() {
		query = query.Where("created_at between ? and ?", param.Time.Start, param.Time.End)
	}
	err = query.Find(&user).Error
	return
}

func (u *UserService) GetAllLen() (l int64) {
	initialization.DB.Model(&model.User{}).Count(&l)
	return l
}
